#!/bin/bash

nargs=$#
if [ $nargs -ne 1 ]
then
	echo "Usage: ./modem_reset <state>    # where state is 1 or 0"
fi

state=$1

# Check if gpio21 folder exists (ie. gpio pin 21 has been 'exported', if not, 'export' it
if [ ! -e /sys/class/gpio/gpio21/direction ]; then
	echo "Setting up pin 21 as GPIO"
	sudo sh -c 'echo 21 > /sys/class/gpio/export'
	if [ $? != 0 ]; then exit 1; fi
fi

dir=`cat /sys/class/gpio/gpio21/direction`

# Check GPIO direction
if [ "$dir" != "out" ]; then
	echo "Setting pin to output"
	sudo sh -c 'echo out > /sys/class/gpio/gpio21/direction'
	if [ $? != 0 ]; then exit 1; fi
fi

current_state=`cat /sys/class/gpio/gpio21/value`

# Check current state
if [ "$current_state" == "$state" ]; then
	echo "Pin 21 already in state "$state
	exit 0
fi

# Modem switch chip (MIC2505) is active low so 0 for poweron and 1 for poweroff
echo "Switching modem power to "$state"..."
if [ "$state" == 0 ]; then
	sudo sh -c 'echo 0 > /sys/class/gpio/gpio21/value'
	exit $?
fi
if [ "$state" == 1 ]; then
        sudo sh -c 'echo 1 > /sys/class/gpio/gpio21/value'
        exit $?
fi

